using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JoyfulHomeJourney.BackEnd.Infrastructure.Atrributes;
using JoyfulHomeJourney.BackEnd.Infrastructure.Dtos.Requests.Objects;
using JoyfulHomeJourney.BackEnd.Infrastructure.Dtos.Responses;
using JoyfulHomeJourney.BackEnd.Infrastructure.Dtos.Responses.Objects;
using JoyfulHomeJourney.BackEnd.Infrastructure.EFCore;
using JoyfulHomeJourney.BackEnd.Server.EFCore;
using JoyfulHomeJourney.BackEnd.Server.Instances.Extends.Requests;
using JoyfulHomeJourney.BackEnd.Server.Instances.Extends.Responses;
using JoyfulHomeJourney.BackEnd.Server.Interfaces;
using Microsoft.EntityFrameworkCore;
namespace JoyfulHomeJourney.BackEnd.Server.Instances
{
/// <summary>
/// 一个类包含了服务类所需的所有仓库表的实例，仅提供给该服务类使用，请将所有服务类所需的仓库表的实例都放在该类中。
/// 仓库表的实例指提供了操作数据库指定表的所有方法的对象
/// </summary>
	internal class DictionarysEF
	{
		public DictionarysEF(DbContext dbContext)
		{
			dictionarysServerEF = new DictionarysServerEF(dbContext);
            sysDictionaryTypesServerEF=new SysDictionaryTypesServerEF(dbContext);
		}
		public DictionarysServerEF dictionarysServerEF { get; set; }
        public SysDictionaryTypesServerEF sysDictionaryTypesServerEF { get; set; }
	}
	[InjectClass]
	public class DictionarysServer : IDictionarysServer
	{
		private readonly DictionarysEF _dictionarysEF;//包含所有所需仓库表实现的对象
		// 请不要修改该构造方法,也无需添加属性，而应该在上面的EF类中添加属性和构造函数赋值语句
		public DictionarysServer(DbContext dbContext)
		{
			_dictionarysEF = new DictionarysEF(dbContext);
		}
        private async Task<bool> Exist(string id)
        {
            return await _dictionarysEF.dictionarysServerEF.Query(d => d.DId == id).AnyAsync();
        }
        private async Task<bool> ExistChildren(string id)
        {
            return await _dictionarysEF.dictionarysServerEF.Query(d => d.DParentId == id).AnyAsync();
        }
        public async Task<ResponseApiDto> AddAsync(RequestDictionarysDto dto)
        {
            return ResponseApiDto.Create(await _dictionarysEF.dictionarysServerEF.AddAsync(dto.ToCreateEntity()));
        }
        public async Task<ResponseApiDto> DeleteAsync(RequestDictionarysDto dto)
        {
            if (!await Exist(dto.id))
            {
                return ResponseApiDto.Fail("字典不存在");
            }
            if (await ExistChildren(dto.id))
            {
                return ResponseApiDto.Fail("请先删除字典子级");
            }
            return ResponseApiDto.Create(await _dictionarysEF.dictionarysServerEF.DeleteAsync(dto.ToDeleteEntity()));
        }
        public async Task<ResponseApiDto> UpdateAsync(RequestDictionarysDto dto)
        {
            if (!await Exist(dto.id))
            {
                return ResponseApiDto.Fail("字典不存在");
            }
            return ResponseApiDto.Create(await _dictionarysEF.dictionarysServerEF.UpdateAllProperNotNullAsync(dto.ToUpdateEntity()));
        }
        public async Task<ResponseApiDto> PaginationAsync(int page, int limit)
        {
            int total = 0;
            List<ResponseDictionarysDto> data = new List<ResponseDictionarysDto>();
            List<Dictionarys> dictionaryss = await _dictionarysEF.dictionarysServerEF.Pagination1(d => true, false, d => d.DCreateTime, out total, page, limit).ToListAsync();
            foreach (var dictionarys in dictionaryss)
            {
                data.Add(dictionarys.ToResponseDto());
            }
            return ResponseApiDto.Success("数据已获取", new ResponsePaginationDto { total = total, data = data });
        }

        public async Task<ResponseApiDto> GetCustomerIndustry()
        {
            var dictionaryTypes = _dictionarysEF.sysDictionaryTypesServerEF.Query(d => d.DtKey == "customer_industry").Select(d => d.DtId).SingleOrDefault();
            List<ResponseDictionarysDto> data = new List<ResponseDictionarysDto>();
            List<Dictionarys> dictionaryss = await _dictionarysEF.dictionarysServerEF.Query(d => dictionaryTypes.Contains(d.DDictionaryTypeId), false, d => d.DCreateTime).ToListAsync();
            foreach (var dictionarys in dictionaryss)
            {
                data.Add(dictionarys.ToResponseDto());
            }
            return ResponseApiDto.Success("数据已获取", new ResponsePaginationDto { data = data });
        }

        public async Task<ResponseApiDto> GetCustomerLevel()
        {
            var dictionaryTypes = _dictionarysEF.sysDictionaryTypesServerEF.Query(d => d.DtKey == "customer_level").Select(d => d.DtId).SingleOrDefault();
            List<ResponseDictionarysDto> data = new List<ResponseDictionarysDto>();
            List<Dictionarys> dictionaryss = await _dictionarysEF.dictionarysServerEF.Query(d => dictionaryTypes.Contains(d.DDictionaryTypeId), false, d => d.DCreateTime).ToListAsync();
            foreach (var dictionarys in dictionaryss)
            {
                data.Add(dictionarys.ToResponseDto());
            }
            return ResponseApiDto.Success("数据已获取", new ResponsePaginationDto { data = data });
        }

        public async Task<ResponseApiDto> GetCustomerSource()
        {
            var dictionaryTypes = _dictionarysEF.sysDictionaryTypesServerEF.Query(d => d.DtKey == "customer_source").Select(d => d.DtId).SingleOrDefault();
            List<ResponseDictionarysDto> data = new List<ResponseDictionarysDto>();
            List<Dictionarys> dictionaryss = await _dictionarysEF.dictionarysServerEF.Query(d => dictionaryTypes.Contains(d.DDictionaryTypeId), false, d => d.DCreateTime).ToListAsync();
            foreach (var dictionarys in dictionaryss)
            {
                data.Add(dictionarys.ToResponseDto());
            }
            return ResponseApiDto.Success("数据已获取", new ResponsePaginationDto { data = data });
        }

        public async Task<ResponseApiDto> GetDictionaryListByDictionaryTypeKey(string key)
        {
            var dictionaryTypeId = (await _dictionarysEF.sysDictionaryTypesServerEF.Query(d => d.DtKey == key).SingleOrDefaultAsync())?.DtId;
            if (dictionaryTypeId == null)
            {
                return ResponseApiDto.Fail("没有该键值");
            }
            List<ResponseDictionarysDto> result = new List<ResponseDictionarysDto>();
            List<Dictionarys> dictionarys = await _dictionarysEF.dictionarysServerEF.Query(d => d.DDictionaryTypeId == dictionaryTypeId && d.DParentId == null).ToListAsync();
            foreach (var dictionary in dictionarys)
            {
                var d = dictionary.ToResponseDto();
                d.subCount = await _dictionarysEF.dictionarysServerEF.Query(e => e.DParentId == dictionary.DId).CountAsync();
                result.Add(d);
            }
            return ResponseApiDto.Success("数据已获取", result);
        }
        public async Task<ResponseApiDto> GetDictionaryTreeByDictionaryTypeKey(string key)
        {
            var dictionaryTypeId = (await _dictionarysEF.sysDictionaryTypesServerEF.Query(d => d.DtKey == key).SingleOrDefaultAsync())?.DtId;
            if (dictionaryTypeId == null)
            {
                return ResponseApiDto.Fail("没有该键值");
            }
            List<ResponseDictionarysDto> result = new List<ResponseDictionarysDto>();
            List<Dictionarys> dictionarys = await _dictionarysEF.dictionarysServerEF.Query(d => d.DDictionaryTypeId == dictionaryTypeId && d.DParentId == null).ToListAsync();
            List<Dictionarys> subDictionarys = await _dictionarysEF.dictionarysServerEF.Query(d => d.DDictionaryTypeId == dictionaryTypeId && d.DParentId != null).ToListAsync();
            result = await GetDictionaryTree(dictionarys, subDictionarys);
            return ResponseApiDto.Success("数据已获取", result);
        }
        private async Task<List<ResponseDictionarysDto>> GetDictionaryTree(List<Dictionarys> dictionarys, List<Dictionarys> subDictionarys)
        {
            List<ResponseDictionarysDto> result = new List<ResponseDictionarysDto>();
            for (int i = 0; i < dictionarys.Count; i++)
            {
                Dictionarys dictionary = dictionarys[i];
                ResponseDictionarysDto r = dictionary.ToResponseDto();
                r.dictionarys = await GetDictionaryTree(subDictionarys.Where(d => d.DParentId == dictionary.DId).ToList(), subDictionarys);
                result.Add(r);
            }
            return result;
        }
        public async Task<ResponseApiDto> GetDictionaryListByParentId(string parentId)
        {
            List<ResponseDictionarysDto> result = new List<ResponseDictionarysDto>();
            List<Dictionarys> dictionarys = await _dictionarysEF.dictionarysServerEF.Query(d => d.DParentId == parentId).ToListAsync();
            foreach (var dictionary in dictionarys)
            {
                var d = dictionary.ToResponseDto();
                d.subCount = await _dictionarysEF.dictionarysServerEF.Query(e => e.DParentId == dictionary.DId).CountAsync();
                result.Add(d);
            }
            return ResponseApiDto.Success("数据已获取", result);
        }
        public async Task<ResponseApiDto> DetailAsync(string id)
        {
            ResponseDictionarysDto result = (await _dictionarysEF.dictionarysServerEF.Query(d => d.DId == id).SingleOrDefaultAsync()).ToResponseDto();
            result.subCount = await _dictionarysEF.dictionarysServerEF.Query(d => d.DParentId == result.id).CountAsync();
            return ResponseApiDto.Success("数据已获取", result);
        }

        public async Task<ResponseApiDto> GetFollowWay()
        {
            var dictionaryTypes = _dictionarysEF.sysDictionaryTypesServerEF.Query(d => d.DtKey == "follow_way").Select(d => d.DtId).SingleOrDefault();
            List<ResponseDictionarysDto> data = new List<ResponseDictionarysDto>();
            List<Dictionarys> dictionaryss = await _dictionarysEF.dictionarysServerEF.Query(d => dictionaryTypes.Contains(d.DDictionaryTypeId), false, d => d.DCreateTime).ToListAsync();
            foreach (var dictionarys in dictionaryss)
            {
                data.Add(dictionarys.ToResponseDto());
            }
            return ResponseApiDto.Success("数据已获取", new ResponsePaginationDto { data = data });
        }
    }
}
